﻿using System;
using System.Threading;
using System.Threading.Tasks;
using Core.RabbitMQBus.Common;
using Core.RabbitMQBus.EventBus;
using Core.RabbitMQBus.Extensions;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace RabbitMQBusTest
{
    class Program
    {
        private static IRabbitMqPublisher _rabbitMqPublisher;
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            IServiceCollection services = new ServiceCollection();
            services.AddLogging();
            services.AddTransient<ILoggerFactory, LoggerFactory>();
            services.AddTransient<ITestService, TestService>();
            services.RegisterRabbitMQ(e => new RabbitMQOptions() { HostName = "localhost" });
            services.RabbitMQRegisterSubscriber("RabbitMQBusTest", "Service");
            //构建容器
            IServiceProvider serviceProvider = services.BuildServiceProvider();
            // 创建ConsoleLogProvider并根据日志类目名称（CategoryName）生成Logger实例
            //解析
            _rabbitMqPublisher = serviceProvider.GetService<IRabbitMqPublisher>();
            Publisher();

            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureServices(e => { e.AddLogging(); })
                .UseStartup<Program>();

        public static void Publisher()
        {
            for (int i = 0; i < 100000; i++)
            {
                _rabbitMqPublisher.Publish("PublishTest1", "测试" + i);
                _rabbitMqPublisher.Publish("PublishTest2", "测试" + i);
            }
        }
    }
    public class TestService : ITestService, ISubscribe
    {
        [Subscribe(queueName: "PublishTest1")]
        public async Task<ExecuteMethodResult> Test(string message)
        {
            //Thread.Sleep(2000);
            Console.WriteLine(message + "PublishTest1");
            return await Task.FromResult(ExecuteMethodResult.Success());
        }

        [Subscribe(queueName: "PublishTest2")]
        public async Task<ExecuteMethodResult> Test1(string message)
        {

            Console.WriteLine(message + "PublishTest2");
            return await Task.FromResult(ExecuteMethodResult.Success());
        }
    }

    public interface ITestService
    {

    }
}
